package com.treetao.union.mall.api.exception;

import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import com.treetao.union.core.exception.DevMException;
import com.treetao.union.db.model.vo.RestResponse;

import lombok.extern.slf4j.Slf4j;

@ControllerAdvice
@Slf4j
public class GlobalApiControllerExceptionHandler {

	// 异常处理方法：
	// 根据特定的异常返回指定的 HTTP 状态码
	@ResponseStatus(value = HttpStatus.BAD_REQUEST) // 400
	@ExceptionHandler(ConstraintViolationException.class)
	@ResponseBody
	public RestResponse handleValidationException(ConstraintViolationException ex) {
		log.error(ex.getMessage());
		Set<ConstraintViolation<?>> errors = ex.getConstraintViolations();
		StringBuilder strBuilder = new StringBuilder();
		for (ConstraintViolation<?> violation : errors) {
			strBuilder.append(violation.getMessage() + "\n");
		}
		return RestResponse.failure(strBuilder.toString());
	}

	// 通用异常的处理，返回500
	@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR) // 500
	@ExceptionHandler(Exception.class)
	@ResponseBody
	public RestResponse handleException(Exception ex) {
		ex.printStackTrace();
		//log.error(ex.getMessage());
		RestResponse resp = RestResponse.failure(ex.getMessage());
		if (ex instanceof DevMException) {
			DevMException me = (DevMException) ex;
			resp.setMessage(me.getMessage());
			resp.setCode(me.getCode());
		}
		return resp;
	}
}
